package com.shangqing.document_management.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.shangqing.document_management.entity.User;
import com.shangqing.document_management.handler.AdminHandler;
import com.shangqing.document_management.jwt.PassToken;
import com.shangqing.document_management.jwt.Token;
import com.shangqing.document_management.jwt.UserLoginToken;
import com.shangqing.document_management.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * 使用拦截器获取并验证token
 */
@Slf4j
public class SysInterceptor implements HandlerInterceptor {
    @Autowired
    AdminService adminService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
        log.info("进入拦截器=====");
        String token=request.getHeader("token"); //从http请求头中得到token
        // 如果不是映射到方法就直接跳过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod) handler;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken的注释 ，如果有的话，就直接跳过
        if(method.isAnnotationPresent(PassToken.class)){
            PassToken passToken=method.getAnnotation(PassToken.class);
            if(passToken.required()){
                return true;
            }
        }
        // 检查是否有需要用户登录权限的注解，
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken=method.getAnnotation(UserLoginToken.class);
            if(userLoginToken.required()) {
                //执行认证
                if (token == null) {
                    throw new RuntimeException("没有token，请重新登陆");
                }
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                    log.info("拿到userid"+userId);
                } catch (JWTDecodeException j){
                    throw new RuntimeException("401");
            }
            User user=adminService.selectUserById(Integer.parseInt(userId));
                if(user==null){
                    throw  new RuntimeException("用户不存在，请重新登录");
                }
                //验证token
                JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                    log.info("验证token"+jwtVerifier.verify(token));
                }catch (JWTVerificationException j){
                    throw new RuntimeException("401");
                }
                return  true;

            }

        }
        return true;

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception {

    }
}
